# 根据房屋面积预测房屋价格
# 1.准备数据
# 2.利用数据找乘加运算中的未知参数(训练/学习)
# 3.模型训练
# 4.模型预测与评估
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
import random

house_data = pd.read_excel('class/the price data.xlsx')
X = house_data['the house square'].values
X_mean = X.mean()
X_std = X.std()
# 归一化操作
X = (X - X_mean) / X_std
y = house_data['the house price'].values
k = sp.symbols('k')
b = sp.symbols('b')

x = X
y_pred = k * x + b
mse_sym = (((y_pred - y) ** 2)).mean()    # 这里是在算loss，他用了mse函数表达loss
# 对损失函数求关于k和b的偏导数
dk_mse = sp.diff(mse_sym, k)
db_mse = sp.diff(mse_sym, b)
 
#指定k、b的初始值为随机值
k_val = random.randint(-10,10)
b_val = random.randint(-10,10)
 
#利用梯度下降求解loss，即mse_sym的极小值。最重要的是，这个过程能够获得k和b的最佳值。
iter = 5000
learning_rate = 0.01
for i in range(iter):
    dk_mse_val = dk_mse.subs({k: k_val, b: b_val})
    db_mse_val = db_mse.subs({k: k_val, b: b_val})
    k_val = k_val - dk_mse_val * learning_rate
    b_val = b_val - db_mse_val * learning_rate
print(k_val,b_val,mse_sym.subs({k: k_val, b: b_val}))

# 4.预测
x = (54 - X_mean) / X_std
y_pred_54 = k_val * x + b_val
print(f'y_pred_54:{y_pred_54}')



# 5.finally:summarize
'''
1.准备数据:X:特征,y:标签,并且以numpy的格式表达
2.准备模型:
3.准备loss函数(mse:均方误差)
4.根据loss函数,利用梯度下降求解loss极小值,从而获得最佳的参数值
5.检验参数是否能用,比如看看mse的值符不符合要求,
(如果不能用):X在用之前需要进行scalar,即进行归一化处理(X-X.mean())/X.std()
6.根据模型进行预测
'''